//
//  AppDelegate.swift
//  flowerpot
//
//  Created by fyname on 15/9/17.
//  Copyright © 2015年 senhe. All rights reserved.
//

import UIKit
import Starscream
import SwiftyJSON
import CryptoSwift

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate

let log: XCGLogger = {
    // Setup XCGLogger
    let log = XCGLogger.defaultInstance()
    log.xcodeColorsEnabled = true // Or set the XcodeColors environment variable in your scheme to YES
    log.xcodeColors = [
        .Verbose: .lightGrey,
        .Debug: .darkGrey,
        .Info: .darkGreen,
        .Warning: .orange,
        .Error: XCGLogger.XcodeColor(fg: UIColor.redColor(), bg: UIColor.whiteColor()), // Optionally use a UIColor
        .Severe: XCGLogger.XcodeColor(fg: (255, 255, 255), bg: (255, 0, 0)) // Optionally use RGB values directly
    ]
    
    #if USE_NSLOG // Set via Build Settings, under Other Swift Flags
        log.removeLogDestination(XCGLogger.constants.baseConsoleLogDestinationIdentifier)
        log.addLogDestination(XCGNSLogDestination(owner: log, identifier: XCGLogger.constants.nslogDestinationIdentifier))
        log.logAppDetails()
        #else
        
        let logPath: NSURL = appDelegate.cacheDirectory.URLByAppendingPathComponent("SENHE_Log.txt")
        log.setup(.Debug, showThreadName: true, showLogLevel: true, showFileNames: true, showLineNumbers: true, writeToFile: logPath)
    #endif
    
    return log
    }()


@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,WebSocketDelegate{

    var window: UIWindow?
    
    var username:String = ""
    var password:String = ""

    let documentsDirectory: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.endIndex - 1]
        }()
    
    let cacheDirectory: NSURL = {
        let urls = NSFileManager.defaultManager().URLsForDirectory(.CachesDirectory, inDomains: .UserDomainMask)
        return urls[urls.endIndex - 1]
        }()
    
    func exceptionHandler(exception : NSException) {
        print(exception)
        print(exception.callStackSymbols)
    }
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        
        //消息通知
        notification(application)
       
        NSThread.sleepForTimeInterval(2.0)//延长3秒
        SingletonLoginSocket.sharedInstance.webSocket.delegate = self
        initMenu()
        isLogin()
        initUMSocia()
        loadFlag()
        return true
    }
    
    func loadFlag(){
        NSUserDefaults.standardUserDefaults().setBool(false, forKey: "load")
    }
    
    func notification(application: UIApplication){
        if (UIDevice.currentDevice().systemVersion as NSString).floatValue >= 8 {
            //APService.registerForRemoteNotificationTypes(
            //UIUserNotificationType.Badge.rawValue |
            //UIUserNotificationType.Sound.rawValue |
            //UIUserNotificationType.Alert.rawValue,
            //categories: nil)
            
            let userSettings = UIUserNotificationSettings(forTypes: [.Badge, .Sound, .Alert], categories: nil)
            application.registerUserNotificationSettings(userSettings)
            
        }
        
        //APService.setupWithOption(launchOptions)
    }
    
    func initMenu(){

        let sliderMenuController = SliderMenuController(mainTabBarController:Common.mainTabBarController,homeNavigationController:Common.homeNavigationController,leftViewController:Common.menuVC,backImage:UIImage(named:("back"))!)
        window = UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.rootViewController = sliderMenuController
        window?.makeKeyAndVisible()
        
        log.debug("侧菜单栏加载完成!")
    }
    
    func initUMSocia(){
        
        //增加友盟SDK第三方登陆组件
        // 设置Appkey
        UMSocialData.setAppKey("56557a2467e58e59910005fb")
        //打开新浪微博的SSO开关，设置新浪微博回调地址，这里必须要和你在新浪微博后台设置的回调地址一致。若在新浪后台设置我们的回调地址，“http://sns.whalecloud.com/sina2/callback”，这里可以传nil
        UMSocialSinaSSOHandler.openNewSinaSSOWithAppKey("2923156246", redirectURL: "http://sns.whalecloud.com/sina2/callback")

       
        
        //增加友盟SDK第三方统计组件
        MobClick.startWithAppkey(Common.UMkey, reportPolicy: BATCH, channelId: "android")
        /** 设置是否对日志信息进行加密, 默认NO(不加密). */
        MobClick.setEncryptEnabled(true)
        /** 设置是否开启background模式, 默认YES. */
        MobClick.setBackgroundTaskEnabled(true)

        //增加友盟SDK第三方分享组件
        UMSocialConfig.setFinishToastIsHidden(true, position: UMSocialiToastPositionCenter)
        
        //设置微信AppId，设置分享url，默认使用友盟的网址
        UMSocialWechatHandler.setWXAppId("wxd930ea5d5a258f4f", appSecret: "db426a9829e4b49a0dcac7b4162da6b6", url: "http://www.umeng.com/social")
        //设置手机QQ的AppId，指定你的分享url，若传nil，将使用友盟的网址
        UMSocialQQHandler.setQQWithAppId("1104898884", appKey: "OI3vT3SWzKDQ5PAi", url: "http://www.umeng.com/social")
        UMSocialQQHandler.setSupportWebView(true)
        
        //设置QQ分享纯图片，默认分享图文消息
        UMSocialData.defaultData().extConfig.qqData.qqMessageType = UMSocialQQMessageTypeImage
        //设置微信好友分享纯图片
        UMSocialData.defaultData().extConfig.wechatSessionData.wxMessageType = UMSocialWXMessageTypeImage
        //设置微信朋友圈分享纯图片
        UMSocialData.defaultData().extConfig.wechatTimelineData.wxMessageType = UMSocialWXMessageTypeImage
    }
    
    func isLogin(){
        
        let un = NSUserDefaults.standardUserDefaults().objectForKey("username")
        let pd = NSUserDefaults.standardUserDefaults().objectForKey("password")
        
        
        
        if(un == nil || pd == nil){
            Common.rootViewController.mainTabBarController.view.addSubview(Common.loginVC.view)
            Common.rootViewController.showHome()
            log.debug("未登录跳转登录页")
        }else{
                
            //Common.login(un, password: pd,callback: loginCallback )
            
            username = un as! String
            password = pd as! String
            
            print("password:  \(password)")
            
            let dataeEcrypted = NSData(base64EncodedString: password, options: NSDataBase64DecodingOptions(rawValue: 0))
            
            let decrypted: NSData = try! dataeEcrypted!.decrypt(AES(key: Common.key, iv: Common.iv))
            
            // Convert back to a string
            let base64Decoded = NSString(data: decrypted, encoding: NSUTF8StringEncoding)
            
            print("Decoded:  \(base64Decoded!)")
            
            
            let up = "\(username):\(base64Decoded!)"
            log.debug(up)
            SingletonLoginSocket.sharedInstance.webSocket.writeString(up)
        }
    }
    
    
    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        
        UIApplication.sharedApplication().cancelAllLocalNotifications()
        
        let notification = UILocalNotification()
        //notification.fireDate = NSDate().dateByAddingTimeInterval(1)
        //setting timeZone as localTimeZone
        notification.timeZone = NSTimeZone.localTimeZone()
        notification.repeatInterval = NSCalendarUnit.Calendar
        notification.alertTitle = "This is a local notification"
        notification.alertBody = "Hey,It's great to see you again"
        notification.alertAction = "OK"
        notification.soundName = UILocalNotificationDefaultSoundName
        //setting app's icon badge
        notification.applicationIconBadgeNumber = 1
        
        var userInfo:[NSObject : AnyObject] = [NSObject : AnyObject]()
        userInfo["kLocalNotificationID"] = "LocalNotificationID"
        userInfo["key"] = "Attention Please"
        notification.userInfo = userInfo
        
        //UIApplication.sharedApplication().scheduleLocalNotification(notification)
        //UIApplication.sharedApplication().presentLocalNotificationNow(notification)
        application.presentLocalNotificationNow(notification)
        
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
    
    //微信与微博集成：添加系统回调
    func application(application: UIApplication, handleOpenURL url: NSURL) -> Bool {
        return UMSocialSnsService.handleOpenURL(url)
    }
    func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
        return UMSocialSnsService.handleOpenURL(url)
    }
    
    
    func websocketDidConnect(socket: WebSocket){
        print("初始化已经连接服务器")
        
        
    }
    
    func websocketDidDisconnect(socket: WebSocket, error: NSError?){
        print("连接服务器断开")
    }
    
    func websocketDidReceiveMessage(socket: WebSocket, text: String){
        print("初始化服务器返回数据:\(text)")
        
        let json = JSON(data: text.dataUsingEncoding(NSUTF8StringEncoding)!)
        //var uid:String?
        
        print("初始化json:\(json)")
        
        if(json["msgCode"].stringValue == "666666"){
            
            
            if(json["result"]["username"].stringValue == username){
                print(json["result"]["username"].stringValue)
                Common.rootViewController.mainTabBarController.view.addSubview(Common.indexVC.view)
                Common.rootViewController.mainTabBarController.view.bringSubviewToFront(Common.rootViewController.mainTabBarController.tabBar)
                Common.rootViewController.showHome()
                
                //统计用户
                MobClick.profileSignInWithPUID(username)
                CozyLoadingActivity.hide(success: true, animated: true)
            }
            
        }else if(json["msgCode"].stringValue == "999998"){
            print("消息状态:"+json["msgCode"].stringValue)
            print("消息状态:"+json["result"]["bmw_id"].stringValue)
            print("消息状态:"+json["result"]["bmw_line"].stringValue)
            let us = UserStatusDO()
            us.userId = json["result"]["bmw_id"].stringValue
            us.userStatus = json["result"]["bmw_line"].stringValue
            
            UserStatus.setUserStatus(us)
            
        }else if(json["msgCode"].stringValue == "999997"){
            print("消息状态:"+json["msgCode"].stringValue)

            //let um = UserMsgDO()
            //um.userId = ""
            //um.userContent = ""
            //UserMsg.setUserContent(um)
            
        }else{
            CozyLoadingActivity.hide(success: false, animated: true)
            print("密码错误!")
        }
        
    }
    func websocketDidReceiveData(socket: WebSocket, data: NSData){
        
    }

}

